import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    //客户端不需要手动指定
    private DatagramSocket socket = null;

    private String serverIp;

    private int serverPort;

    public UdpEchoClient(String ip, int port) throws SocketException {
        serverIp = ip;
        serverPort = port;
        socket = new DatagramSocket();
    }

    public void start() throws IOException {
        System.out.println("客户端上线!");
        //循环去发请求
        while(true){
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入：");
            String request = sc.next();

            //1.将服务器的地址和端口号放进数据报，然后发送
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), 0, request.getBytes().length, InetAddress.getByName(serverIp), serverPort);
            socket.send(requestPacket);

            //2.等待接受服务器发来的响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024], 1024);
            socket.receive(responsePacket);

            String response = new String(responsePacket.getData(), 0, responsePacket.getData().length);
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        new UdpEchoClient("127.0.0.1", 8080).start();
    }
}
